package com.hu.common.util.adm;

import com.hu.common.domain.dto.TreeDTO;
import org.springframework.util.CollectionUtils;
import org.xmind.core.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName ExportTreeToXMind22
 * @author 355760
 */
public class ExportTreeToXMindUtil {
    private static IWorkbook workbook;

    public static void exportLabel(TreeDTO nodes, String fileName) throws IOException, CoreException {

        IWorkbookBuilder builder = Core.getWorkbookBuilder();
        workbook = builder.createWorkbook();
        ISheet sheet = workbook.getPrimarySheet();
        // 创建根主题
        ITopic rootTopic = sheet.getRootTopic();
        rootTopic.setTitleText(nodes.getName()+"(Root)");
        // 将树形数据转换为XMind中的主题对象
        traverseTreeLabel(rootTopic, nodes);
        // 保存XMind文件
        OutputStream output = new FileOutputStream(fileName);
        workbook.save(output);
        output.close();
    }

    private static void traverseTreeLabel(ITopic parentTopic, TreeDTO node) {
        if (!CollectionUtils.isEmpty(node.getChildren())) {
            for (TreeDTO child : node.getChildren()) {
                ITopic topic = workbook.createTopic();
                topic.setTitleText(child.getNameC()+"("+child.getName()+")");
                parentTopic.add(topic);
                traverseTreeLabel(topic, child);
            }
        }
    }

    public static void export(TreeDTO nodes, String fileName) throws IOException, CoreException {

        IWorkbookBuilder builder = Core.getWorkbookBuilder();
        workbook = builder.createWorkbook();
        ISheet sheet = workbook.getPrimarySheet();
        // 创建根主题
        ITopic rootTopic = sheet.getRootTopic();
        rootTopic.setTitleText(nodes.getName());
        // 将树形数据转换为XMind中的主题对象
        traverseTree(rootTopic, nodes);
        // 保存XMind文件
        OutputStream output = new FileOutputStream(fileName);
        workbook.save(output);
        output.close();
    }

    private static void traverseTree(ITopic parentTopic, TreeDTO node) {
        if (!CollectionUtils.isEmpty(node.getChildren())) {
            for (TreeDTO child : node.getChildren()) {
                ITopic topic = workbook.createTopic();
                topic.setTitleText(child.getName());
                parentTopic.add(topic);
                traverseTree(topic, child);
            }
        }
    }

    public static boolean isXMind8Below(byte[] fileBytes) {
        byte[] bytes1 = new byte[16];
        int idx = 0;
        for (int i = 110; i < 119; i++) {
            bytes1[idx] = fileBytes[i];
            idx++;
        }
        String fileHeader = new String(bytes1, StandardCharsets.UTF_8);
        return fileHeader.contains("xmind");
    }
}
